package com.example.medicine.controller;


import com.example.medicine.Bean.*;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.Mapper.zhengzhuangMapper;
import com.example.medicine.Mapper.zhongyaoMapper;
import com.example.medicine.Mapper.zhongyao_zhengzhuangMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import java.util.List;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/zyxx")
public class ZhongyaoController {
    Subject subject = SecurityUtils.getSubject();
    private static final String UPLOADED_FOLDER = "D:/FileRecv/uploadImages/";
    @Autowired
    private zhongyaoMapper zhongyaoMapper;
    @Autowired
    private yonghuMapper yonghuMapper;
    @Autowired
    private zhongyao_zhengzhuangMapper zhongyaoZhengzhuangMapper;
    @Autowired
    private zhengzhuangMapper zhengzhuangMapper;
//    @RequiresPermissions("中药管理")
    @GetMapping("/")
    public List<zhongyaoWithCompany> getZhongyaoList(){
        log.info("getZhongyaoList获取中药信息");
        yonghu yonghu = yonghuMapper.getById(subject.getPrincipal().toString());
        if(yonghu.getType().equals("中药+方剂录入")){
            return zhongyaoMapper.getByUser(subject.getPrincipal().toString());
        }
        return zhongyaoMapper.getAll();
    }
    @RequiresPermissions("中药管理")
    @GetMapping("/zhengzhuang")
    public List<zhengzhuang> getZhengzhuang(){
        log.info("getZhongyaoList获取症状信息");
        return zhengzhuangMapper.getAll();
    }

    @RequiresPermissions("中药管理")
    @PostMapping("/")
    public void insertZhengzhuang(@RequestParam("zhongyao") String zhongyaoJson,
                           @RequestParam(value = "image", required = false) MultipartFile image,
                           @RequestParam("zhengzhuang") String zhengZhuang
    ) throws IOException {
        log.info("insertZhengzhuang添加中药start");
        String imageName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        zhongyao zhongyao = objectMapper.readValue(zhongyaoJson, zhongyao.class);

        if (image != null && !image.isEmpty())
            imageName = fileLoad(image);
        zhongyao.setTupian(imageName);
        zhongyao.setCreateuser(subject.getPrincipal().toString());
        zhongyaoMapper.insert(zhongyao);
        if(zhengZhuang!=null) {
            int zhongyaoId=(int)zhongyao.getId();
            String[] val=zhengZhuang.split(",");
            for(String x : val){
                zhongyao_zhengzhuang zhongyao_zhengzhuang=new zhongyao_zhengzhuang();
                zhongyao_zhengzhuang.setZhongyao(zhongyaoId);
                zhongyao_zhengzhuang.setZhengzhuang(x);
                zhongyaoZhengzhuangMapper.insert(zhongyao_zhengzhuang);
            }
        }
        log.info("insertZhengzhuang添加中药end");
    }
    @RequiresPermissions("中药管理")
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatchBook(@RequestParam("file") MultipartFile file) {
        log.info("insertBatchBook中药批量导入");
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }

            List<zhongyao> zhongyaoList = new ArrayList<>();
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                zhongyao zhongyao = new zhongyao();
                for(int i=0;i<=18;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 -> zhongyao.setYaoming(value);
                        case 1 -> zhongyao.setLadingming(value);
                        case 2 -> zhongyao.setStandardMedicineName(value);
                        case 3 -> zhongyao.setMedicineClassifyName(value);
                        case 4 -> zhongyao.setBieming(value);
                        case 5 -> zhongyao.setChufangming(value);
                        case 6 -> zhongyao.setYaowuleixing(value);
                        case 7 -> zhongyao.setShifoushiyong(value);
                        case 8 -> zhongyao.setChandi(value);
                        case 9 -> zhongyao.setChuchu(value);
                        case 10 -> zhongyao.setPaozhi(value);
                        case 11 -> zhongyao.setYaoxiaoleibie(value);
                        case 12 -> zhongyao.setXing(value);
                        case 13 -> zhongyao.setWei(value);
                        case 14 -> zhongyao.setGuijing(value);
                        case 15 -> zhongyao.setDuxing(value);
                        case 16 -> zhongyao.setGongneng(value);
                        case 17 -> zhongyao.setZhuzhi(value);
                        case 18 -> zhongyao.setYongfayongliang(value);
                    }
                }
                zhongyao.setCreateuser(subject.getPrincipal().toString());
                zhongyaoList.add(zhongyao);
            }
            // 将数据批量插入数据库
            if (!zhongyaoList.isEmpty()) {
                zhongyaoMapper.batchInsertZhongyao(zhongyaoList);
            }
            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }
    @RequiresPermissions("中药管理")
    @PutMapping("/")
    public void updateZhongyao(@RequestParam("zhongyao") String zhongyaoJson,
                               @RequestParam(value = "image", required = false) MultipartFile image) throws IOException {
        log.info("updateZhongyao修改中药start");
        String imageName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        zhongyao zhongyao = objectMapper.readValue(zhongyaoJson, zhongyao.class);

        if (image != null && !image.isEmpty())
            imageName = fileLoad(image);
        zhongyao.setTupian(imageName);
        zhongyaoMapper.update(zhongyao);
        log.info("updateZhongyao修改中药end");
    }

    @RequiresPermissions("中药管理")
    @PutMapping("/zhengzhuang")
    public void getZhengzhuang(@RequestParam("id") int zhongyaoId,@RequestParam("zhengzhuang") String zhengZhuang){
        log.info("getZhengzhuang获取症状信息");
        if(zhengZhuang!=null) {
            zhongyaoZhengzhuangMapper.deleteByZhongyao(zhongyaoId);
            if(zhengZhuang.equals(""))
                return;
            String[] val=zhengZhuang.split(",");
            for(String x : val){
                zhongyao_zhengzhuang zhongyao_zhengzhuang=new zhongyao_zhengzhuang();
                zhongyao_zhengzhuang.setZhongyao(zhongyaoId);
                zhongyao_zhengzhuang.setZhengzhuang(x);
                zhongyaoZhengzhuangMapper.insert(zhongyao_zhengzhuang);
            }
        }
    }

    @RequiresPermissions("中药管理")
    @PutMapping("/shenhe")
    public void updateShenhe(@RequestBody zhongyao zhongyao){
        log.info("updateShenhe中药审核");
        zhongyao.setShr(subject.getPrincipal().toString());
        zhongyaoMapper.updateShenhe(zhongyao);
    }
    private String fileLoad(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename();    //获取原始的文件名
        //用UUID作为新文件名，扩展名不变  避免同名覆盖
        String newName = UUID.randomUUID()+ "." + fname.substring(fname.lastIndexOf(".")+1);
        File dest_file = new File( UPLOADED_FOLDER + newName );
        file.transferTo(dest_file);
        return newName;
    }

    @RequiresPermissions("中药管理")
    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable long id){
        log.info("deleteBook中药删除");
        zhongyaoMapper.deleteById(id);
    }

}
